package com.ittao.taoaicodemother.event;

import com.ittao.taoaicodemother.model.entity.App;
import com.ittao.taoaicodemother.service.AppService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 应用状态更新事件监听器
 */
@Component
@Slf4j
public class AppStatusUpdateEventListener {

    @Resource
    private AppService appService;

    @EventListener
    public void handleAppStatusUpdate(AppStatusUpdateEvent event) {
        try {
            log.info("处理应用状态更新事件，appId: {}, generateStatus: {}, taskId: {}",
                    event.getAppId(), event.getGenerateStatus(), event.getCurrentTaskId());

            // 获取应用信息
            App app = appService.getById(event.getAppId());
            if (app == null) {
                log.warn("应用不存在，无法更新状态，appId: {}", event.getAppId());
                return;
            }

            // 创建更新对象
            App updateApp = new App();
            updateApp.setId(event.getAppId());
            updateApp.setEditTime(LocalDateTime.now());

            // 设置生成状态
            if (event.getGenerateStatus() != null) {
                updateApp.setGenerateStatus(event.getGenerateStatus());
            }

            // 设置当前任务ID
            if (event.getCurrentTaskId() != null) {
                updateApp.setCurrentTaskId(event.getCurrentTaskId());
            } else {
                // 如果任务ID为null，表示清空当前任务ID
                updateApp.setCurrentTaskId(null);
            }

            // 设置部署状态
            if (event.getDeployStatus() != null) {
                updateApp.setDeployStatus(event.getDeployStatus());
            }

            // 执行更新
            boolean result = appService.updateById(updateApp);
            if (result) {
                log.info("应用状态更新成功，appId: {}", event.getAppId());
            } else {
                log.error("应用状态更新失败，appId: {}", event.getAppId());
            }

        } catch (Exception e) {
            log.error("处理应用状态更新事件异常，appId: {}, error: {}",
                    event.getAppId(), e.getMessage(), e);
        }
    }
}
